<template>
    <div style="background-color: #EDEDED;" class="container " ref="contentRef" @scroll="handleScroll">
        <div class="top_bar">
            <!-- 总计标题 -->
            <div class="total_title">总金额</div>
            <!-- 总金额数值 -->
            <div class="total_money" ref="moneyRef">{{ formatMoneyNum(982000.99, 1) }}</div>
        </div>
        <!-- 银行卡面板 -->
        <div class="card_panel"
            :style="{ transform: `translateY(${options.scrollTranslateRem}rem)`, overflow: options.parentScroll ? 'scroll' : 'hidden', }"
            @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
            <div class="card_panel_content">
                <!-- <div class="card_panel_content_item"
        :style="{ backgroundColor: '#' + Math.floor(Math.random() * 16777215).toString(16) }" v-for="index in 40"
        :key="index"> </div> -->
            </div>
        </div>
        <LayoutIndex />
    </div>
</template>

<script setup>
import { ref, onUnmounted, reactive } from "vue"
import LayoutIndex from "./layout/Index.vue"
import AddCardVue from '@/views/account/AddCardVue.vue'

const moneyRef = ref(null)
const intervalId = ref(null)
// 格式化钱
const formatMoneyNum = (num, type) => {
    if (type == 1) {
        updateMoney(0, num)
    }
    else {
        const options = {
            style: 'currency',
            currency: 'CNY',
        };
        return num.toLocaleString("zh-CN", options);
    }
}
// 更新金额的函数，包含滚动动画  
const updateMoney = (oldVal, newVal) => {
    // 初始化当前值  
    let currentValue = parseInt(oldVal, 10);
    // 创建定时器，逐步增加或减少金额  
    intervalId.value = setInterval(() => {
        if (currentValue !== newVal) {
            const type = Math.sign(newVal - currentValue); // 根据方向增加或减少1  
            // 生成一个当前值与最终值之间的随机数
            const randomNum = Math.floor(Math.random() * Math.abs(newVal - currentValue));
            if (type === 1) {
                currentValue += randomNum;
            } else {
                currentValue -= randomNum;
            }
            const options = {
                style: 'currency',
                currency: 'CNY',
            };
            // moneyRef.value.textContent = currentValue.toLocaleString("zh-CN", options); // 格式化为带千位分隔符的数字  
        } else {
            clearInterval(intervalId.value); // 达到目标值后停止定时器  
        }
    }, 10); // 每10毫秒更新一次金额  
};


const options = reactive({
    touchDistance: 0,//记录开始触摸的距离
    isScroll: false,//内容区域超出是否滚动
    scrollDistance: 0,//移动的距离
    scrollTranslateRem: 5.0462,//内容盒子距离顶部的距离
    scrollTranslateRemMax: 2.5462,//内容盒子上极限移动距离
    scrollTranslateRemDownMax: 5.0462,//内容盒子下极限移动距离

    // 父级盒子是否滚动
    parentScroll: false,
    // 父级盒子滚动距离
    parentScrollDistance: 0,
})


const contentRef = ref(null);
const handleScroll = () => {
    const scrollTop = contentRef.value.scrollTop;
    console.log("滚动高度:", scrollTop);
    if (scrollTop <= 145) {
        // 当滚动高度小于等于100px时，动态设置头部高度
        console.log("Loaded");
        if (!options.parentScroll) {
            return
        }
        options.parentScroll = false;

    } else {
        // 当滚动高度大于100px时，固定头部高度为100px
        console.log("Loading");
        if (options.parentScroll) {
            return
        }
        options.parentScroll = true;
    }
}
// 将REM转换为PX
function remToPx(remValue) {
    // 获取当前文档的根元素的字体大小（即1REM的值）
    const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    // 将REM值乘以根元素的字体大小，得到相应的PX值
    return remValue * fontSize;
}

// 将PX转换为REM
function pxToRem(pxValue) {
    // 获取当前文档的根元素的字体大小（即1REM的值）
    const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    // 将PX值除以根元素的字体大小，得到相应的REM值
    return pxValue / fontSize;
}


const handleTouchStart = (event) => {
    let startY = event.touches[0].clientY;
    console.log("startY:", startY);
    options.touchDistance = startY;
}
const handleTouchMove = (event) => {
    if (!options.touchDistance) {
        return;
    }
    // console.log("event.touches[0].clientY:", event.touches[0].clientY);
    let deltaY = event.touches[0].clientY - options.touchDistance;
    // 判断滚动距离
    if (deltaY > 0) {
        options.parentScroll = true;
        return
        if (options.scrollTranslateRemDownMax <= options.scrollTranslateRem) {
            return
        }
        // 向下划动
        options.scrollTranslateRem = options.scrollTranslateRem + pxToRem(deltaY);
    } else {
        return
        if (options.scrollTranslateRemMax >= options.scrollTranslateRem) {
            return
        }
        // 向上划动
        console.log(deltaY, Math.abs(pxToRem(deltaY)), 'pxToRem(deltaY)');
        //记录滚动距离
        // options.scrollDistance = Math.abs(pxToRem(deltaY));
        options.scrollTranslateRem = options.scrollTranslateRem + pxToRem(deltaY);
    }
}

const handleTouchEnd = (event) => {
    console.log("handleTouchEnd:");
    options.touchDistance = 0;
}

onUnmounted(() => {
    console.log("组件卸载了");
    clearInterval(intervalId.value); // 组件卸载时清除定时器
})
</script>

<style lang="scss" scoped>
.container {
    height: 100vh;
    overflow: scroll;
    position: relative;
    z-index: 99;

    .top_bar {
        background: #1D2027 url("@/assets/Frame.png") no-repeat center center;
        background-size: 100% 100%;
        height: 10.6154rem;
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        z-index: -1;
        transition: all 0.3s ease;
        /* 添加动画效果 */

        .total_title {
            transform: translateY(1.9231rem);
            text-align: center;
            font-size: .3077rem;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: .4615rem;
            color: rgba(204, 204, 204, 1);
        }

        .total_money {
            transform: translateY(1.9231rem);
            text-align: center;
            font-size: .9231rem;
            font-weight: 700;
            letter-spacing: 0px;
            line-height: 1.1538rem;
            color: rgba(255, 255, 255, 1);
        }

    }

    .card_panel {
        background-color: #1D2027;
        transition: all 0.3s ease;
        height: calc(100vh - 1.3rem);

        .card_panel_content {
            background-color: #fff;
            height: 29.88rem;
            border-radius: .5128rem .5128rem 0 0;


            .card_panel_content_item {
                height: 30px;
                background-color: aquamarine;
            }
        }
    }
}
</style>